package com.wlz;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 *  编程式 事务  测试
 * @author wlz
 * @date 2022-06-07  9:17 下午
 */
public class MainProgramStarter {

	private static String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
	private static String user = "root";
	private static String password = "123456";



	public static void main(String[] args) {

		// 获取数据源
		final DataSource ds = new DriverManagerDataSource(url, user, password);
		// 编程式事务
		final TransactionTemplate template = new TransactionTemplate();
		// 设置事务管理器
		template.setTransactionManager(new DataSourceTransactionManager(ds));

		template.execute(new TransactionCallback<Object>() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				Connection conn = DataSourceUtils.getConnection(ds);
				Object savePoint = null;
				try {
					{
						// 插入
						PreparedStatement prepare = conn.
								prepareStatement(
										"insert INTO account_info (accountId,blance) VALUES (?,?,)");
						prepare.setString(1, "111");
						prepare.setDouble(2, 100);
						prepare.executeUpdate();
					}
					// 设置保存点
					savePoint = status.createSavepoint();
					{
						// 插入
						PreparedStatement prepare = conn.
								prepareStatement(
										"insert INTO account_info (accountId,blance) VALUES (?,?)");
						prepare.setString(1, "222");
						prepare.setDouble(2, 200);
						prepare.executeUpdate();
					}
					{
						// 更新
						PreparedStatement prepare = conn.prepareStatement(
								"UPDATE account_info SET blance= blance+100 where accountId=?");
						prepare.setString(1, "111");
						prepare.executeUpdate();
						//int i=1/0;

					}
				} catch (SQLException e) {
					e.printStackTrace();
				} catch (Exception e) {
					System.out.println("更新失败");
					if (savePoint != null) {
						status.rollbackToSavepoint(savePoint);
					} else {
						status.setRollbackOnly();
					}
				}
				return null;
			}
		});
	}

}
